<?php

namespace app\admin\controller;

use think\Controller;
use think\captcha\Captcha;
use think\Request;
use think\facade\Session;
use think\Validate;
use app\admin\model\AdminModel;

class Login extends Controller
{
    /**
     * 登录页
     * @param Request $request
     * @return mixed|\think\response\Json
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $validate = new Validate([
                'captcha|验证码' => 'require|captcha|token',
                'username|用户名' => 'require|length:4,18',
                'password|密码' => 'require|length:6,18'
            ]);
            if ($validate->check($request->param())) {
                $username = $request->param('username');
                $password = $request->param('password');
                $online = $request->param('online');
                $admin_model = new AdminModel;
                $res = $admin_model->checkUser($username, $password, $online);
                if ($res['status'] == 'n') {
                    $res['token'] = $request->token();
                }
                return json($res);
            } else {
                return json(['status' => 'n', 'info' => $validate->getError(), 'token' => $request->token()]);
            }
        }
        return $this->fetch();
    }

    /**
     * 验证码
     * @return \think\Response
     */
    public function getCaptcha()
    {
        $config = [
            'fontSize' => 50,
            'length' => 4,
            // 关闭验证码杂点
            'useNoise' => true,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        setcookie('PHPSESSID', '', time() - 1, '/');
        Session::delete('username');
        $this->error('退出成功', url('admin/login/index'));
    }
}
